<template>
	<view class="points-container">
		<!-- 积分头部信息 -->
		<view class="points-header">
			<view class="points-info" @click="toPointsRecord">
				<text class="points-title">我的积分</text>
				<text class="points-value">{{ userExtInfo.points }}</text>
				<text class="points-desc">积分可用于兑换商品</text>
			</view>
			<view class="points-info" @click="toPointsCards">
				<text class="points-title">我的积分卡</text>
				<text class="points-value">{{ userExtInfo.pointsCards }}</text>
				<text class="points-desc">积分卡可用于兑换商品</text>
			</view>
			<view class="points-rules" @click="showRules">
				<text class="rules-text">积分规则</text>
				<text class="rules-icon">?</text>
			</view>
		</view>

		<!-- 积分商品分类 -->
		<scroll-view class="category-tabs" scroll-x="true" show-scrollbar="false" scroll-with-animation="true">
			<view class="tabs-container">
				<view class="tab-item" :class="{ active: activeIndex === index }" v-for="(item, index) in categoryList"
					:key="index" @click="switchTab(index)">
					<text class="tab-text">{{ item.group_name }}</text>
				</view>
			</view>
		</scroll-view>

		<!-- 积分商品列表 -->
		<view class="products-list">
			<!-- 商品列表 -->
			<view class="product-item" v-for="(product, index) in pointsProducts" :key="index"
				@click="toProductDetail(product)">
				<image :src="$tools.buildUrl(product.white_back_ground_pic_url)" mode="aspectFill"
					class="product-image" lazy-load></image>
				<view class="product-info">
					<text class="product-name">{{ product.spu_name }}</text>
					<text class="product-desc">{{ product.sku_name }}</text>
					<view class="product-bottom">
						<!-- 兑换方式显示 -->
						<view class="exchange-methods">
							<!-- 积分兑换 -->
							<view v-if="[1,3].includes(product.exchange_type)" class="method-item">
								<text class="method-label">积分:</text>
								<text class="points-text">{{ product.exchange_points }}</text>
							</view>
							<!-- 积分卡兑换 -->
							<view v-if="[2,3].includes(product.exchange_type)" class="method-item">
								<text class="method-label">积分卡:</text>
								<view class="cards-requirement">
									<text v-for="(item, cardindex) in product.exchange_cards" :key="cardindex"
										class="card-req" :class="item.level">
										{{ item.count }}{{ item.level }}
									</text>
								</view>
							</view>
						</view>
						<view class="exchange-btn" :class="{ disabled: !canExchange(product) }"
							@click.stop="toProductDetail(product)">
							<text class="btn-text">{{ getExchangeButtonText(product) }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<view v-if="!hasSearched && pointsProducts.length === 0" class="empty-state">
				<text class="empty-text">暂无商品</text>
			</view>

			<!-- 加载状态 -->
			<view v-if="hasSearched" class="loading-state">
				<text class="loading-text">加载中...</text>
			</view>
		</view>

		<!-- 积分记录入口 -->
		<view class="points-record" @click="toPointsRecord">
			<text class="record-text">查看积分记录</text>
			<text class="record-arrow">></text>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'

	export default {
		data() {
			return {
				// 用户扩展信息（非登录相关）
				userExtInfo: {
					points: 0,
					pointsCards: 0,
					cardsList: []
				},
				activeIndex: 0, // 当前选中的分类
				searchKeyword: '',
				hasSearched: false,
				recordCount: 0,
				page: 1,
				limit: 10,
				categoryList: [],
				pointsProducts: []
			}
		},
		computed: {
			...mapGetters(['isLogin', 'userInfo']),

			currentCategory() {
				return this.categoryList[this.activeIndex] || {}
			}
		},
		onLoad(options) {
			// 如果有传入分类名称，自动选中对应分类
			if (options.id) {
				const index = this.categoryList.findIndex(item => item.id === options.id)
				if (index >= 0) {
					this.activeIndex = index
				}
			} else if (options.group_name) {
				const index = this.categoryList.findIndex(item => item.group_name === options.group_name)
				if (index >= 0) {
					this.activeIndex = index
				}
			}
			this.loadCategory()
		},
		onShow() {
			this.loadUserExtInfo();
		},

		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh() {
			if (!this.hasSearched) {
				this.page = 1
				this.recordCount = 0
				this.pointsProducts = []
				this.loadDataList()
			}
		},

		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom() {
			// 下拉触底，先判断是否有请求正在进行中
			// 以及检查当前请求页数是不是小于数据总页数，如符合条件，则发送请求
			const page = this.page
			const limit = this.limit
			const recordCount = this.recordCount
			if (!this.hasSearched && page * limit < recordCount) {
				this.page++
				setTimeout(() => {
					this.loadDataList()
				}, 500)
			}
		},
		methods: {
			// 搜索事件处理
			onSearch(searchQuery) {
				this.searchKeyword = searchQuery
				this.page = 1
				this.recordCount = 0
				this.pointsProducts = []
				this.loadDataList()
			},
			loadUserExtInfo() {
				this.$api.user.GetUserExtInfo2().then(res => {
					this.userExtInfo = {
						points: res.data.points,
						pointsCards: res.data.pointsCards,
						cardsList: this.$tools.parseJsonObject(res.data.cardsList)
					}
				})
			},
			// 查询分类
			loadCategory() {
				this.$api.good.GetProductGroup({
					group_type: 2
				}).then(res => {
					this.categoryList = [{
						id: '',
						group_name: '全部',
						group_icon: '',
						back_ground_image: ''
					}]
					this.categoryList = this.categoryList.concat(res.data)
					this.onSearch(this.searchKeyword)
				})
			},
			// 查询分类商品
			loadDataList() {
				if (this.hasSearched) {
					return false
				}

				this.hasSearched = true
				const group_id = this.activeIndex >= 0 ? this.categoryList[this.activeIndex].id : ''
				this.$api.good.GetPointProductList({
					page: this.page,
					limit: this.limit,
					group_id: group_id,
					keyword: this.searchKeyword
				}).then(res => {
					this.hasSearched = false
					this.recordCount = res.count
					res.data.forEach(item => {
						item.exchange_cards = this.$tools.parseJsonObject(item.exchange_cards);
					})
					this.pointsProducts = this.pointsProducts.concat(res.data)
				}).catch(err => {
					this.hasSearched = false
					if (this.page > 0) {
						this.page--
					}
				})
			},
			// 切换分类
			switchTab(index) {
				this.activeIndex = index
				this.onSearch(this.searchKeyword)
			},
			// 检查是否可以兑换   兑换方式：1-积分 2积分卡 3两者均可
			canExchange(product) {
				if (product.exchange_type === 1) {
					return this.userExtInfo.points >= product.exchange_points
				} else if (product.exchange_type === 2) {
					return this.canExchangeWithCards(product.exchange_cards)
				} else if (product.exchange_type === 3) {
					return this.userExtInfo.points >= product.exchange_points || this.canExchangeWithCards(product
						.exchange_cards)
				}
				return false
			},
			// 检查积分卡是否足够
			canExchangeWithCards(cardsRequired) {
				if (!cardsRequired) return false
				if (!(this.userExtInfo.cardsList && this.userExtInfo.cardsList.length > 0)) return false
				for (let index in cardsRequired) {
					const ii = this.userExtInfo.cardsList.findIndex(item => item.scorecard === cardsRequired[index]
						.level && item.sy_points >= cardsRequired[index].count);
					if (ii < 0) {
						return false;
					}
				}
				return true
			},
			// 获取兑换按钮文本
			getExchangeButtonText(product) {
				if (!this.canExchange(product)) {
					if (product.exchange_type === 1) {
						return '积分不足'
					} else if (product.exchange_type === 2) {
						return '积分卡不足'
					} else {
						return '条件不足'
					}
				}
				return '立即兑换'
			},
			// 跳转到商品详情
			toProductDetail(product) {
				if (!this.canExchange(product)) {
					uni.showToast({
						title: this.getExchangeButtonText(product),
						icon: 'none'
					})
					return
				}

				uni.navigateTo({
					url: `/points-package/product/points-detail?id=${product.spu_id}&sku_id=${product.id}`
				})
			},
			// 查看积分记录
			toPointsRecord() {
				uni.navigateTo({
					url: '/points-package/record/points-record?point_type=1'
				})
			},
			// 跳转到积分卡页面
			toPointsCards() {
				uni.navigateTo({
					url: '/points-package/record/points-cards'
				})
			},
			// 显示积分规则
			showRules() {
				uni.navigateTo({
					url: '/points-package/rules/points-rules'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.points-container {
		background-color: #f8f9fa;
		min-height: 100vh;
		padding-bottom: 160rpx;
	}

	/* 积分头部 */
	.points-header {
		background: linear-gradient(135deg, #52a58a 0%, #6bb6a3 100%);
		padding: 60rpx 30rpx 40rpx;
		color: white;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.points-info {
		flex: 1;
	}

	.points-title {
		font-size: 28rpx;
		opacity: 0.9;
		display: block;
		margin-bottom: 10rpx;
	}

	.points-value {
		font-size: 48rpx;
		font-weight: bold;
		display: block;
		margin-bottom: 8rpx;
	}

	.points-desc {
		font-size: 24rpx;
		opacity: 0.8;
	}

	.points-rules {
		display: flex;
		align-items: center;
		background-color: rgba(255, 255, 255, 0.2);
		padding: 12rpx 20rpx;
		border-radius: 30rpx;
	}

	.rules-text {
		font-size: 24rpx;
		margin-right: 8rpx;
	}

	.rules-icon {
		font-size: 20rpx;
		width: 32rpx;
		height: 32rpx;
		background-color: rgba(255, 255, 255, 0.3);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 分类标签 */
	.category-tabs {
		background-color: white;
		border-bottom: 1rpx solid #f0f0f0;
		height: 100rpx;
	}

	.tabs-container {
		display: flex;
		align-items: center;
		height: 100%;
		padding: 0 30rpx;
		white-space: nowrap;
	}

	.tab-item {
		flex: none;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		padding: 8rpx 24rpx;
		margin-right: 20rpx;
		border-radius: 50rpx;
		transition: all 0.3s ease;
		white-space: nowrap;
		min-width: max-content;
	}

	.tab-item:last-child {
		margin-right: 30rpx;
	}

	.tab-item.active {
		background-color: #52a58a;
	}

	.tab-item.active .tab-text {
		color: white;
		font-weight: bold;
	}

	.tab-text {
		font-size: 28rpx;
		color: #666;
		white-space: nowrap;
		transition: color 0.3s ease;
	}

	/* 商品列表 */
	.products-list {
		padding: 20rpx 30rpx;
	}

	.product-item {
		background-color: white;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
		display: flex;
		padding: 20rpx;
		transition: all 0.3s ease;
		transform: translateY(0);
	}

	.product-item:active {
		transform: translateY(2rpx);
		box-shadow: 0 1rpx 8rpx rgba(0, 0, 0, 0.12);
	}

	.product-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 12rpx;
		margin-right: 20rpx;
		background-color: #f5f5f5;
	}

	.product-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.product-name {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 8rpx;
	}

	.product-desc {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 20rpx;
	}

	.product-bottom {
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
	}

	/* 兑换方式 */
	.exchange-methods {
		flex: 1;
		margin-right: 20rpx;
	}

	.method-item {
		display: flex;
		align-items: center;
		margin-bottom: 8rpx;
	}

	.method-item:last-child {
		margin-bottom: 0;
	}

	.method-label {
		font-size: 22rpx;
		color: #666;
		margin-right: 8rpx;
		min-width: 60rpx;
	}

	.points-text {
		font-size: 28rpx;
		font-weight: bold;
		color: #ff6b35;
	}

	.cards-requirement {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
	}

	.card-req {
		font-size: 22rpx;
		font-weight: bold;
		padding: 2rpx 8rpx;
		border-radius: 8rpx;
		margin-right: 6rpx;
		margin-bottom: 4rpx;
		color: white;
	}

	.card-req.S {
		background-color: #ff6b35;
	}

	.card-req.A {
		background-color: #52a58a;
	}

	.card-req.B {
		background-color: #3498db;
	}

	.card-req.C {
		background-color: #9b59b6;
	}

	.card-req.D {
		background-color: #95a5a6;
	}

	.exchange-btn {
		background: linear-gradient(135deg, #52a58a 0%, #6bb6a3 100%);
		color: white;
		padding: 16rpx 32rpx;
		border-radius: 30rpx;
		font-size: 24rpx;
		box-shadow: 0 4rpx 12rpx rgba(82, 165, 138, 0.3);
		transition: all 0.3s ease;
		transform: translateY(0);
	}

	.exchange-btn:active {
		transform: translateY(1rpx);
		box-shadow: 0 2rpx 8rpx rgba(82, 165, 138, 0.4);
	}

	.exchange-btn.disabled {
		background: #e0e0e0;
		box-shadow: none;
		transform: none;
	}

	.btn-text {
		font-size: 24rpx;
	}

	/* 积分记录入口 */
	.points-record {
		background-color: white;
		margin: 20rpx 30rpx;
		padding: 30rpx;
		border-radius: 16rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.record-text {
		font-size: 28rpx;
		color: #333;
	}

	.record-arrow {
		font-size: 24rpx;
		color: #999;
	}

	/* 空状态和加载状态 */
	.empty-state,
	.loading-state {
		text-align: center;
		padding: 80rpx 0;
	}

	.empty-text,
	.loading-text {
		font-size: 28rpx;
		color: #999;
	}

	/* 响应式优化 */
	@media screen and (max-width: 750rpx) {
		.points-header {
			padding: 40rpx 20rpx 30rpx;
		}

		.category-tabs {
			height: 80rpx;
		}

		.tabs-container {
			padding: 0 20rpx;
		}

		.tab-item {
			padding: 12rpx 20rpx;
			margin-right: 15rpx;
		}

		.tab-item:last-child {
			margin-right: 20rpx;
		}

		.products-list {
			padding: 15rpx 20rpx;
		}
	}
</style>
